package cn.smbms.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;

import cn.smbms.config.AlioauthConfig;
import cn.smbms.pojo.AlipayUser;
import cn.smbms.service.AlioauthService;

@Controller
@RequestMapping("/api")
public class AlioathController {

	@Autowired
	private AlioauthConfig alioauthConfig;

	@Autowired
	private AlioauthService alioauthService;

	String redirect_uri = "http://alipay.ngrok2.xiaomiqiu.cn/smbms2/api/returnurl";

	// http://localhost:8088/smbms2/api/oauth2app
	@RequestMapping("oauth2app")
	public String oauth2app() {
		String url = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=" + alioauthConfig.getAppID()
				+ "&redirect_uri=" + redirect_uri;
		return "redirect:" + url;
	}

	// http://localhost:8088/smbms2/api/oauth2auth
	@RequestMapping("oauth2auth")
	public String oauth2auth() {
		String url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + alioauthConfig.getAppID()
				+ "&scope=auth_user&redirect_uri=" + redirect_uri;
		return "redirect:" + url;
	}

	@RequestMapping("getUser")
	public void getUser(String token, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		// 查询用户信息
		AlipayUser user = alioauthService.getUserInfo(token);
		out.println("user=" + user);
	}

	/**
	 * 
	 * @param app_id
	 * @param app_auth_code 第三方授权code
	 * @param response
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws AlipayApiException
	 */
	@RequestMapping("returnurl")
	public void returnurl(String app_id, String auth_code, String app_auth_code, HttpServletResponse response,
			HttpServletRequest request) throws IOException, AlipayApiException {
		// 访问令牌
		PrintWriter out = response.getWriter();
		if (auth_code != null && !"".equals(auth_code)) {
			out.println("访问令牌 auth_code=" + auth_code);
			//
			String token = alioauthService.getAccessToken(auth_code);
			out.println("token=" + token);
			// 查询用户信息
			AlipayUser user = alioauthService.getUserInfo(token);
			out.println("user=" + user);
		}
		// 应用授权
		else if (app_auth_code != null && !"".equals(app_auth_code)) {
			out.println("应用授权 app_auth_code=" + app_auth_code);
			//
			String token = alioauthService.getAppAuthToken(app_auth_code);
			out.println("token=" + token);
			// 查询授权信息
			String userId = alioauthService.getAuthInfo(token);
			out.println("userId=" + userId);
		} else {
			out.println("授权码出错：auth_code=[" + auth_code + "] 或 app_auth_code=[" + app_auth_code + "]");
		}
	}

}
